//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.example.fashion.android.util.FileUtil;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.os.StatFs;
import android.text.TextUtils;


import com.example.fashion.android.globar.AppManager;
import com.example.fashion.android.globar.Constant;
import com.example.fashion.android.util.ImageUtil.ImageUtil;
import com.example.fashion.android.util.LogUtil.L;
import com.example.fashion.android.util.SecurityUtil.SecurityUtil;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Comparator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FileUtil {
    private static String downloadRootDir = null;
    private static String imageDownloadDir = null;
    private static String fileDownloadDir = null;
    private static String cacheDownloadDir = null;
    private static String dbDownloadDir = null;
    private static int freeSdSpaceNeededToCache = 209715200;

    public FileUtil() {
    }

    public static Bitmap getBitmapFromSD(File file, int type, int desiredWidth, int desiredHeight) {
        Bitmap bitmap = null;

        try {
            if (!isCanUseSD()) {
                return null;
            }

            if (!file.exists()) {
                return null;
            }

            if (desiredWidth <= 0 || desiredHeight <= 0) {
                type = 2;
            }

            if (type == 0) {
                bitmap = ImageUtil.getCutBitmap(file, desiredWidth, desiredHeight);
            } else if (type == 1) {
                bitmap = ImageUtil.getScaleBitmap(file, desiredWidth, desiredHeight);
            } else {
                bitmap = ImageUtil.getBitmap(file);
            }
        } catch (Exception var6) {
            var6.printStackTrace();
        }

        return bitmap;
    }

    public static Bitmap getBitmapFromSD(File file) {
        Bitmap bitmap = null;

        try {
            if (!isCanUseSD()) {
                return null;
            }

            if (!file.exists()) {
                return null;
            }

            bitmap = ImageUtil.getBitmap(file);
        } catch (Exception var3) {
            var3.printStackTrace();
        }

        return bitmap;
    }

    public static Bitmap getBitmapFromByte(byte[] imgByte, String fileName, int type, int desiredWidth, int desiredHeight) {
        FileOutputStream fos = null;
        DataInputStream dis = null;
        ByteArrayInputStream bis = null;
        Bitmap bitmap = null;
        File file = null;

        try {
            if (imgByte != null) {
                file = new File(imageDownloadDir + fileName);
                if (!file.exists()) {
                    file.createNewFile();
                }

                fos = new FileOutputStream(file);
                boolean e = false;
                bis = new ByteArrayInputStream(imgByte);
                dis = new DataInputStream(bis);
                byte[] buffer = new byte[1024];

                int e1;
                while ((e1 = dis.read(buffer)) != -1) {
                    fos.write(buffer, 0, e1);

                    try {
                        Thread.sleep(500L);
                    } catch (Exception var30) {
                        ;
                    }
                }

                fos.flush();
                bitmap = getBitmapFromSD(file, type, desiredWidth, desiredHeight);
            }
        } catch (Exception var31) {
            var31.printStackTrace();
        } finally {
            if (dis != null) {
                try {
                    dis.close();
                } catch (Exception var29) {
                    ;
                }
            }

            if (bis != null) {
                try {
                    bis.close();
                } catch (Exception var28) {
                    ;
                }
            }

            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception var27) {
                    ;
                }
            }

        }

        return bitmap;
    }

    public static Bitmap getBitmapFromURL(String url, int desiredWidth, int desiredHeight) {
        Bitmap bitmap = null;

        try {
            bitmap = ImageUtil.getBitmap(url, desiredWidth, desiredHeight);
        } catch (Exception var5) {
            L.d(FileUtil.class, "下载图片异常：" + var5.getMessage());
        }

        return bitmap;
    }

    public static Bitmap getBitmapFromSrc(String src) {
        Bitmap bit = null;

        try {
            bit = BitmapFactory.decodeStream(FileUtil.class.getResourceAsStream(src));
        } catch (Exception var3) {
            L.d(FileUtil.class, "获取图片异常：" + var3.getMessage());
        }

        return bit;
    }

    public static Bitmap getBitmapFromAsset(Context context, String fileName) {
        Bitmap bit = null;

        try {
            AssetManager e = context.getAssets();
            InputStream is = e.open(fileName);
            bit = BitmapFactory.decodeStream(is);
        } catch (Exception var5) {
            L.d(FileUtil.class, "获取图片异常：" + var5.getMessage());
        }

        return bit;
    }

    public static Drawable getDrawableFromAsset(Context context, String fileName) {
        Drawable drawable = null;

        try {
            AssetManager e = context.getAssets();
            InputStream is = e.open(fileName);
            drawable = Drawable.createFromStream(is, (String) null);
        } catch (Exception var5) {
            L.d(FileUtil.class, "获取图片异常：" + var5.getMessage());
        }

        return drawable;
    }

    public static String downloadFile(String url, String dirPath) {
        InputStream in = null;
        FileOutputStream fileOutputStream = null;
        HttpURLConnection connection = null;
        String downFilePath = null;
        File file = null;

        String e;
        try {
            if (isCanUseSD()) {
                e = getCacheFileNameFromUrl(url);
                File parentFile = new File(dirPath);
                if (!parentFile.exists()) {
                    parentFile.mkdirs();
                }

                File[] files = parentFile.listFiles();
                String fileName;
                String b;
                if (files != null) {
                    for (int mUrl = 0; mUrl < files.length; ++mUrl) {
                        fileName = files[mUrl].getName();
                        b = fileName.substring(0, fileName.lastIndexOf("."));
                        if (b.equals(e)) {
                            String temp = files[mUrl].getPath();
                            return temp;
                        }
                    }
                }

                URL var42 = new URL(url);
                connection = (HttpURLConnection) var42.openConnection();
                connection.connect();
                fileName = getCacheFileNameFromUrl(url, connection);
                file = new File(dirPath, fileName);
                downFilePath = file.getPath();
                if (file.exists()) {
                    b = file.getPath();
                    return b;
                }

                file.createNewFile();
                in = connection.getInputStream();
                fileOutputStream = new FileOutputStream(file);
                byte[] var43 = new byte[1024];
                boolean var44 = false;

                int var45;
                while ((var45 = in.read(var43)) != -1) {
                    fileOutputStream.write(var43, 0, var45);
                }

                return downFilePath;
            }

            e = null;
        } catch (Exception var40) {
            var40.printStackTrace();
            L.e(FileUtil.class, "有文件下载出错了,已删除");
            if (file != null) {
                file.delete();
            }

            file = null;
            downFilePath = null;
            return downFilePath;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception var39) {
                var39.printStackTrace();
            }

            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (Exception var38) {
                var38.printStackTrace();
            }

            try {
                if (connection != null) {
                    connection.disconnect();
                }
            } catch (Exception var37) {
                var37.printStackTrace();
            }

        }

        return e;
    }

    public static int getContentLengthFromUrl(String Url) {
        int mContentLength = 0;

        try {
            URL e = new URL(Url);
            HttpURLConnection mHttpURLConnection = (HttpURLConnection) e.openConnection();
            mHttpURLConnection.setConnectTimeout(5000);
            mHttpURLConnection.setRequestMethod("GET");
            mHttpURLConnection.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
            mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN");
            mHttpURLConnection.setRequestProperty("Referer", Url);
            mHttpURLConnection.setRequestProperty("Charset", "UTF-8");
            mHttpURLConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
            mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            mHttpURLConnection.connect();
            if (mHttpURLConnection.getResponseCode() == 200) {
                mContentLength = mHttpURLConnection.getContentLength();
            }
        } catch (Exception var4) {
            var4.printStackTrace();
            L.d(FileUtil.class, "获取长度异常：" + var4.getMessage());
        }

        return mContentLength;
    }

    public static String getRealFileNameFromUrl(String url) {
        Object name = null;

        try {
            if (TextUtils.isEmpty(url)) {
                return (String) name;
            }

            URL e = new URL(url);
            HttpURLConnection mHttpURLConnection = (HttpURLConnection) e.openConnection();
            mHttpURLConnection.setConnectTimeout(5000);
            mHttpURLConnection.setRequestMethod("GET");
            mHttpURLConnection.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
            mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN");
            mHttpURLConnection.setRequestProperty("Referer", url);
            mHttpURLConnection.setRequestProperty("Charset", "UTF-8");
            mHttpURLConnection.setRequestProperty("User-Agent", "");
            mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            mHttpURLConnection.connect();
            if (mHttpURLConnection.getResponseCode() == 200) {
                int i = 0;

                while (true) {
                    String mine = mHttpURLConnection.getHeaderField(i);
                    if (mine == null) {
                        break;
                    }

                    if ("content-disposition".equals(mHttpURLConnection.getHeaderFieldKey(i).toLowerCase())) {
                        Matcher m = Pattern.compile(".*filename=(.*)").matcher(mine.toLowerCase());
                        if (m.find()) {
                            return m.group(1).replace("\"", "");
                        }
                    }

                    ++i;
                }
            }
        } catch (Exception var7) {
            var7.printStackTrace();
            L.e(FileUtil.class, "网络上获取文件名失败");
        }

        return (String) name;
    }

    public static String getRealFileName(HttpURLConnection connection) {
        Object name = null;

        try {
            if (connection == null) {
                return (String) name;
            }

            if (connection.getResponseCode() == 200) {
                int e = 0;

                while (true) {
                    String mime = connection.getHeaderField(e);
                    if (mime == null) {
                        break;
                    }

                    if ("content-disposition".equals(connection.getHeaderFieldKey(e).toLowerCase())) {
                        Matcher m = Pattern.compile(".*filename=(.*)").matcher(mime.toLowerCase());
                        if (m.find()) {
                            return m.group(1).replace("\"", "");
                        }
                    }

                    ++e;
                }
            }
        } catch (Exception var5) {
            var5.printStackTrace();
            L.e(FileUtil.class, "网络上获取文件名失败");
        }

        return (String) name;
    }

    public static String getCacheFileNameFromUrl(String url) {
        if (TextUtils.isEmpty(url)) {
            return null;
        } else {
            String name = null;

            try {
                name = SecurityUtil.MD5(url);
            } catch (Exception var3) {
                var3.printStackTrace();
            }

            return name;
        }
    }

    public static String getCacheFileNameFromUrl(String url, HttpURLConnection connection) {
        if (TextUtils.isEmpty(url)) {
            return null;
        } else {
            String name = null;

            try {
                String e = getMIMEFromUrl(url, connection);
                if (TextUtils.isEmpty(e)) {
                    e = ".ab";
                }

                name = SecurityUtil.MD5(url + System.currentTimeMillis()) + e;
            } catch (Exception var4) {
                var4.printStackTrace();
            }

            return name;
        }
    }

    public static String getMIMEFromUrl(String url, HttpURLConnection connection) {
        if (TextUtils.isEmpty(url)) {
            return null;
        } else {
            String suffix = null;

            try {
                if (url.lastIndexOf(".") != -1) {
                    suffix = url.substring(url.lastIndexOf("."));
                    if (suffix.indexOf("/") != -1 || suffix.indexOf("?") != -1 || suffix.indexOf("&") != -1) {
                        suffix = null;
                    }
                }

                if (TextUtils.isEmpty(suffix)) {
                    String e = getRealFileName(connection);
                    if (e != null && e.lastIndexOf(".") != -1) {
                        suffix = e.substring(e.lastIndexOf("."));
                    }
                }
            } catch (Exception var4) {
                var4.printStackTrace();
            }

            return suffix;
        }
    }

    public static byte[] getByteArrayFromSD(String path) {
        byte[] bytes = null;
        ByteArrayOutputStream out = null;

        Object fileSize;
        try {
            File e = new File(path);
            if (isCanUseSD()) {
                if (!e.exists()) {
                    fileSize = null;
                    return (byte[]) fileSize;
                }

                long fileSize1 = e.length();
                FileInputStream in;
                if (fileSize1 > 2147483647L) {
                    return null;
                }

                in = new FileInputStream(path);
                out = new ByteArrayOutputStream(1024);
                byte[] buffer = new byte[1024];
                boolean size = false;

                int size1;
                while ((size1 = in.read(buffer)) != -1) {
                    out.write(buffer, 0, size1);
                }

                in.close();
                bytes = out.toByteArray();
                return bytes;
            }

            fileSize = null;
        } catch (Exception var20) {
            var20.printStackTrace();
            return bytes;
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (Exception var19) {
                    var19.printStackTrace();
                }
            }

        }

        return (byte[]) fileSize;
    }

    public static void writeByteArrayToSD(String path, byte[] content, boolean create) {
        FileOutputStream fos = null;

        try {
            File e = new File(path);
            if (isCanUseSD()) {
                if (!e.exists()) {
                    if (!create) {
                        return;
                    }

                    File parent = e.getParentFile();
                    if (!parent.exists()) {
                        parent.mkdirs();
                        e.createNewFile();
                    }
                }

                fos = new FileOutputStream(path);
                fos.write(content);
                return;
            }
        } catch (Exception var16) {
            var16.printStackTrace();
            return;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception var15) {
                    ;
                }
            }

        }

    }

    public static void writeBitmapToSD(String path, Bitmap bitmap) {
        writeBitmapToSD(path, bitmap, CompressFormat.PNG, 100);
    }

    public static void writeBitmapToSD(String path, Bitmap bitmap, CompressFormat format, int quality) {
        FileOutputStream fos = null;

        try {
            File e = new File(path);
            if (isCanUseSD()) {
                if (!e.exists()) {
                    File parent = e.getParentFile();
                    if (!parent.exists()) {
                        parent.mkdirs();
                        e.createNewFile();
                    }
                }

                fos = new FileOutputStream(path);
                bitmap.compress(format, quality, fos);
                return;
            }
        } catch (Exception var16) {
            var16.printStackTrace();
            return;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception var15) {
                    ;
                }
            }

        }

    }

    public static void copyAssets2SD(Context context, String assetDir, String outDir) {
        try {
            String[] files = context.getAssets().list(assetDir);
            File e = new File(outDir);
            if (!e.exists()) {
                e.mkdirs();
            }

            for (int i = 0; i < files.length; ++i) {
                String fileName = files[i];
                String[] filesChild = context.getAssets().list(fileName);
                if (filesChild != null && filesChild.length > 0) {
                    copyAssets2SD(context, fileName, outDir + "/" + fileName);
                } else {
                    InputStream in = null;
                    if (!TextUtils.isEmpty(assetDir)) {
                        in = context.getAssets().open(assetDir + "/" + fileName);
                    } else {
                        in = context.getAssets().open(fileName);
                    }

                    File outFile = new File(outDir + "/" + fileName);
                    if (outFile.exists()) {
                        outFile.delete();
                    }

                    outFile.createNewFile();
                    FileOutputStream out = new FileOutputStream(outFile);
                    byte[] buf = new byte[1024];

                    int len;
                    while ((len = in.read(buf)) > 0) {
                        out.write(buf, 0, len);
                    }

                    in.close();
                    out.close();
                }
            }
        } catch (Exception var13) {
            var13.printStackTrace();
        }

    }

    public static boolean isCanUseSD() {
        try {
            return Environment.getExternalStorageState().equals("mounted");
        } catch (Exception var1) {
            var1.printStackTrace();
            return false;
        }
    }

    public static void initFileDir(Context context) {
        PackageInfo info = AppManager.getPackageInfo(context);
        String downloadRootPath = File.separator + Constant.DOWNLOAD_ROOT_DIR + File.separator + info.packageName + File.separator;
        String imageDownloadPath = downloadRootPath + Constant.DOWNLOAD_IMAGE_DIR + File.separator;
        String fileDownloadPath = downloadRootPath + Constant.DOWNLOAD_FILE_DIR + File.separator;
        String cacheDownloadPath = downloadRootPath + Constant.CACHE_DIR + File.separator;
        String dbDownloadPath = downloadRootPath + Constant.DB_DIR + File.separator;

        try {
            if (!isCanUseSD()) {
                return;
            }

            File e = Environment.getExternalStorageDirectory();
            File downloadDir = new File(e.getAbsolutePath() + downloadRootPath);
            if (!downloadDir.exists()) {
                downloadDir.mkdirs();
            }

            downloadRootDir = downloadDir.getPath();
            File cacheDownloadDirFile = new File(e.getAbsolutePath() + cacheDownloadPath);
            if (!cacheDownloadDirFile.exists()) {
                cacheDownloadDirFile.mkdirs();
            }

            cacheDownloadDir = cacheDownloadDirFile.getPath();
            File imageDownloadDirFile = new File(e.getAbsolutePath() + imageDownloadPath);
            if (!imageDownloadDirFile.exists()) {
                imageDownloadDirFile.mkdirs();
            }

            imageDownloadDir = imageDownloadDirFile.getPath();
            File fileDownloadDirFile = new File(e.getAbsolutePath() + fileDownloadPath);
            if (!fileDownloadDirFile.exists()) {
                fileDownloadDirFile.mkdirs();
            }

            fileDownloadDir = fileDownloadDirFile.getPath();
            File dbDownloadDirFile = new File(e.getAbsolutePath() + dbDownloadPath);
            if (!dbDownloadDirFile.exists()) {
                dbDownloadDirFile.mkdirs();
            }

            dbDownloadDir = dbDownloadDirFile.getPath();
        } catch (Exception var13) {
            var13.printStackTrace();
        }

    }

    public static int freeSpaceOnSD() {
        StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
        double sdFreeMB = (double) stat.getAvailableBlocks() * (double) stat.getBlockSize() / 1024.0D * 1024.0D;
        return (int) sdFreeMB;
    }

    public static boolean clearDownloadFile() {
        try {
            File e = new File(downloadRootDir);
            deleteFile(e);
            return true;
        } catch (Exception var1) {
            var1.printStackTrace();
            return false;
        }
    }

    public static boolean deleteFile(File file) {
        try {
            if (!isCanUseSD()) {
                return false;
            } else if (file == null) {
                return true;
            } else {
                if (file.isDirectory()) {
                    File[] e = file.listFiles();

                    for (int i = 0; i < e.length; ++i) {
                        deleteFile(e[i]);
                    }
                } else {
                    file.delete();
                }

                return true;
            }
        } catch (Exception var3) {
            var3.printStackTrace();
            return false;
        }
    }

    public static String readAssetsByName(Context context, String name, String encoding) {
        String text = null;
        InputStreamReader inputReader = null;
        BufferedReader bufReader = null;

        try {
            inputReader = new InputStreamReader(context.getAssets().open(name));
            bufReader = new BufferedReader(inputReader);
            String e = null;
            StringBuffer buffer = new StringBuffer();

            while ((e = bufReader.readLine()) != null) {
                buffer.append(e);
            }

            text = new String(buffer.toString().getBytes(), encoding);
        } catch (Exception var16) {
            var16.printStackTrace();
        } finally {
            try {
                if (bufReader != null) {
                    bufReader.close();
                }

                if (inputReader != null) {
                    inputReader.close();
                }
            } catch (Exception var15) {
                var15.printStackTrace();
            }

        }

        return text;
    }

    public static String readRawByName(Context context, int id, String encoding) {
        String text = null;
        InputStreamReader inputReader = null;
        BufferedReader bufReader = null;

        try {
            inputReader = new InputStreamReader(context.getResources().openRawResource(id));
            bufReader = new BufferedReader(inputReader);
            String e = null;
            StringBuffer buffer = new StringBuffer();

            while ((e = bufReader.readLine()) != null) {
                buffer.append(e);
            }

            text = new String(buffer.toString().getBytes(), encoding);
        } catch (Exception var16) {
            var16.printStackTrace();
        } finally {
            try {
                if (bufReader != null) {
                    bufReader.close();
                }

                if (inputReader != null) {
                    inputReader.close();
                }
            } catch (Exception var15) {
                var15.printStackTrace();
            }

        }

        return text;
    }

    public static String getDownloadRootDir(Context context) {
        if (downloadRootDir == null) {
            initFileDir(context);
        }

        return downloadRootDir;
    }

    public static String getImageDownloadDir(Context context) {
        if (downloadRootDir == null) {
            initFileDir(context);
        }

        return imageDownloadDir;
    }

    public static String getFileDownloadDir(Context context) {
        if (downloadRootDir == null) {
            initFileDir(context);
        }

        return fileDownloadDir;
    }

    public static String getCacheDownloadDir(Context context) {
        if (downloadRootDir == null) {
            initFileDir(context);
        }

        return cacheDownloadDir;
    }

    public static String getDbDownloadDir(Context context) {
        if (downloadRootDir == null) {
            initFileDir(context);
        }

        return dbDownloadDir;
    }

    public static int getFreeSdSpaceNeededToCache() {
        return freeSdSpaceNeededToCache;
    }

    public static class FileLastModifSort implements Comparator<File> {
        public FileLastModifSort() {
        }

        public int compare(File arg0, File arg1) {
            return arg0.lastModified() > arg1.lastModified() ? 1 : (arg0.lastModified() == arg1.lastModified() ? 0 : -1);
        }
    }
}
